//
//  ApplyLoanHouseController.swift
//  xiaoqiao
//
//  Created by 冷子豪 on 2017/7/13.
//  Copyright © 2017年 冷子豪. All rights reserved.
//

import UIKit

class ApplyLoanHouseController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    
    @IBOutlet weak var houseTable: UITableView!
    
    var houseList = [House]()
    var delHouseList = [House]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.houseTable.delegate = self
        self.houseTable.dataSource = self
        
        loadData { (list) in
//            print(list)
            // ‘拼接’数组,闭包中定义好的代码在需要的时候执行，需要self，指定语境
            self.houseList += list
            
            // 刷新表格
            self.houseTable.reloadData()
            
            
            
            
        }
    }
    
    /// 利用闭包回调
    private func loadData(completion:@escaping ([House]) -> ()) -> () {
        
        DispatchQueue.global().async {
            print("加载房产信息中……")
            
            Thread.sleep(forTimeInterval: 0.1)
            
            let arrayM = houseViewModel.getHouseListByUserId(userid: user.id!)
            // 主线程回调
            DispatchQueue.main.async(execute: {
                
                // 回调，执行闭包
                completion(arrayM)
            })
        }
    }
    
    //MARK: - 控制器跳转方法
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "house2detail"{
            // 类型转换
            let vc = segue.destination as! ApplyHouseDetailController
            
            // 设置选中的 house，indexPath
            if let indexPath = sender as? IndexPath {
                // indexPath 一定有值
                vc.house = houseList[indexPath.row]
                
                // 设置编辑完成的闭包
                vc.completionCallBack = {
                    // 刷新制定行
                    self.houseTable.reloadRows(at: [indexPath], with: .automatic)
                }
            } else {
                // 新建房产记录
                
                vc.completionCallBack = {
                    
                    // 1. 获取明细控制器的 house
                    guard let h = vc.house,h.numOfCertificate != "" else{
                        return
                    }
                    // 2. 插入到数组顶部
                    self.houseList.insert(h, at: 0)
                    
                    // 3. 刷新表格
                    self.houseTable.reloadData()
                }
            }
        }
        
    }
    
    // MARK: - 代理方法
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
//        houseTable.deselectRow(at: indexPath, animated: true)
        
        // 执行 segue
        performSegue(withIdentifier: "house2detail", sender: indexPath)
    }
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        
        // 提取至已删除队列
        let h = houseList[indexPath.row]
        h.status = "已删除"
        delHouseList.insert(h, at: 0)
        
        // 删除数据源中数据
        houseList.remove(at: indexPath.row)
        
        self.houseTable.reloadData()
        
        
    }
    // MARK: - 数据源方法
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return houseList.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)
        
        cell.textLabel?.text = houseList[indexPath.row].numOfCertificate
        cell.detailTextLabel?.text = houseList[indexPath.row].cityOfHouse
        
        return cell
    }

    
    @IBAction func addHouse(_ sender: Any) {
        // 执行 segue 跳转界面
        performSegue(withIdentifier: "house2detail", sender: nil)
    }
    
    @IBAction func nextClick(_ sender: UIButton) {
        // 合并 现存房产队列 与 已删除房产队列
        // 便于存档已删除旧房产
        arrayHouse = houseList + delHouseList
        if true {
            // 跳转界面 到 申请信息
            performSegue(withIdentifier: "house2apply", sender: nil)
        }
    }
}
